/**
 * @author showtan on 2018/10/10.
 * Func: 定时器封装
 */
import React, { Component } from 'react';
import {
  Text,
  StyleSheet,
  TouchableOpacity
} from 'react-native';
import * as  Animatable from 'react-native-animatable';
import adapt from '../utils/adapt';

class CheckButton extends Component {

  static defaultProps = {
    onClick: null,
    delay: '',
  };
  constructor(props) {
    super(props);
    this.state = {
      vercode: '获取验证码',
      disabled: false
    };
    this.delay = this.props.delay;
  }
  sendVerCode = () => {
    if (this.delay !== this.props.delay) {
      this.delay = this.props.delay;
    }
    this.interval = setInterval(this.timefunc, 1000);
    this.disable();
  }
  timefunc = () => {
    if (this.delay > 0) {
      this.setState({ vercode: this.delay-- + 's后重发', });
    } else {
      this.setState({
        vercode: '重新获取', disabled: false
      });
      this.interval && clearInterval(this.interval);
    }
  }
  enable = () => {
    this.setState({ disabled: false });
  }
  disable = () => {
    this.setState({ disabled: true });
  }
  onPress = () => {
    this.props.onClick(this.enable);
  }
  componentWillUnmount() {
    this.interval && clearInterval(this.interval);
  }
  render() {
    return (
      <Animatable.View animation='zoomIn' duration={500} style={[styles.btnStyle, this.props.btnStyle]}>
        <TouchableOpacity activeOpacity={.6} onPress={this.onPress}>
          <Text style={[styles.titleStyle, this.props.titleStyle]}>{this.state.vercode}</Text>
        </TouchableOpacity>
      </Animatable.View>
    );
  }
}

const styles = StyleSheet.create({
  btnStyle: {
    borderRadius: adapt(5),
    borderWidth: adapt(1),
    borderColor: '#FF773D'
  },
  titleStyle: {
    margin: adapt(6),
    marginVertical: adapt(4),
    fontSize: adapt(10),
    color: '#FF773D'
  }
});
export default CheckButton;